package au.com.mason.propertyTracker.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import au.com.mason.propertyTracker.dao.PropertyDAO;
import au.com.mason.propertyTracker.domain.Property;
import au.com.mason.propertyTracker.domain.SaleProperty;
import au.com.mason.propertyTracker.domain.Suburb;
import au.com.mason.propertyTracker.dto.SearchParameters;
import au.com.mason.propertyTracker.util.HttpClientWrapper;
import au.com.mason.propertyTracker.util.RealEstateResponseParser;

@Service
public class PropertyService {
	private PropertyDAO propertyDAO;
	private SuburbService suburbService;
	
	@Autowired
	public PropertyService(PropertyDAO propertyDAO, SuburbService suburbService) {
		this.propertyDAO = propertyDAO;
		this.suburbService = suburbService;
	}
	
	public List<Property> filterProperties(Suburb suburb, SearchParameters searchParameters) {
		return propertyDAO.filterProperties(suburb, searchParameters);
	}
	
	public void saveProperty(SaleProperty property) {
		property.setDateListed(new Date());
		propertyDAO.save(property);
	}
	
	public void updateProperty(Property property) {
		propertyDAO.update(property);
	}
	
	public Property getProperty(int id) {
		return (Property) propertyDAO.findById(id);
	}
	
	public void deleteProperty(Integer id) {
		propertyDAO.deleteById(id);
	}
	
	public Property findByPropertyId(BigDecimal propertyId) {
		return propertyDAO.findByPropertyId(propertyId);
	}
	
	public Property findByUrl(String url) {
		return propertyDAO.findByUrl(url);
	}
	
	public boolean addProperty(String url, boolean rental) {
		HttpClientWrapper httpClientWrapper = new HttpClientWrapper();
		httpClientWrapper.initAndExecute(url);
		
		RealEstateResponseParser parser = new RealEstateResponseParser(httpClientWrapper.getResponse());
		SaleProperty property = parser.getSaleProperty(url);
		Suburb suburb = suburbService.getSuburb(parser.getSuburbName(), parser.getPostcode());
		property.setSuburb(suburb);
		
		Property dbProperty = findByUrl(url);
		if (dbProperty != null) {
			return false;
		}
		
		saveProperty(property);
		
		return true;
	}
}
